<template>
  <!-- 页面-单据序列管理-设置-添加 -->
  <div>
    <Form
      :model="modelForm"
      ref="editForm"
      class="ivu-form-no-margin-bottom"
      :rules="rule"
      :label-width="100"
    >
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="ruleSegmentField" :label="$t('module.receiptSequence.field')">
            <Select
              :placeholder="$t('module.receiptSequence.selectField')"
              v-model="modelForm.ruleSegmentField"
              
              @on-change="segmentChange"
              :disabled="ruleId!=''"
            >
              <Option
                v-for="item in segmentList"
                :title="item.vsiValue"
                :value="item.vsiKey"
                :key="item.vsiKey"
              >{{ item.vsiValue }}</Option>
            </Select>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="ruleSegmentFieldValue" :label="$t('module.receiptSequence.fieldValue')">
            <Input
              placeholder
              
              v-model="modelForm.ruleSegmentFieldValue"
              :disabled="segmentFieldValueNoEdit"
              :maxlength="50"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="datePattern" :label="$t('module.receiptSequence.dateFormat')">
            <Select
              v-model="modelForm.datePattern"
              
              @on-change="dataChange"
              :disabled="datePatternNoEdit"
            >
              <Option
                v-for="item in dateFormatList"
                :title="item.vsiValue"
                :value="item.vsiKey"
                :key="item.vsiKey"
              >{{ item.vsiValue }}</Option>
            </Select>
            <!-- <Tooltip content="值集编码为：dateFormat" placement="right">
              <Icon type="information-circled" size="18"></Icon>
            </Tooltip>-->
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="seqLength" :label="$t('module.receiptSequence.digit')">
            <Input
              placeholder
              
              v-model="modelForm.seqLength"
              :disabled="seqLengthNoEdit"
              :maxlength="50"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="seqIncrement" :label="$t('module.receiptSequence.stepSize')">
            <Input
              placeholder
              
              v-model="modelForm.seqIncrement"
              :disabled="seqIncrementNoEdit"
              :maxlength="50"
            ></Input>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="seqStartValue" :label="$t('module.receiptSequence.startValue')">
            <Input
              placeholder
              
              v-model="modelForm.seqStartValue"
              :disabled="seqStartValueNoEdit"
              :maxlength="50"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item prop="paramCode" :label="$t('module.receiptSequence.parameterCode')">
            <Input
              placeholder
              
              :disabled="parameterCodeValueEdit"
              v-model="modelForm.paramCode"
              :maxlength="50"
            ></Input>
          </Form-item>
        </Col>
        <Col span="12" style="border:none;">
          <Form-item prop="paramName" :label="$t('module.receiptSequence.parameterName')">
            <Input
              placeholder
              
              :disabled="parameterNameInputEdit"
              v-model="modelForm.paramName"
              :maxlength="50"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border:none;">
          <Form-item
            prop="parameterDefaultInput"
            :label="$t('module.receiptSequence.parameterDefault')"
          >
            <Input
              placeholder
              
              v-model="modelForm.paramDefaultValue"
              :disabled="parameterDefaultInputEdit"
              :maxlength="50"
            ></Input>
          </Form-item>
        </Col>
        <!-- 状态 -->
        <Col span="12" style="border:none;">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled" size="small">
              <Radio :label="1">
                <span>{{$t('common.enable')}}</span>
              </Radio>
              <Radio :label="0">
                <span>{{$t('common.disable')}}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <Row>
        <Col span="12" style="border:none;">
          <Form-item prop="ruleSegmentOrder" :label="$t('common.sort')">
            <InputNumber
              placeholder
              style="width:100%"
              v-model="modelForm.ruleSegmentOrder"
              :min="1"
              :max="50"
            ></InputNumber>
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
import { GetValueSetByCode } from "./common.js";
import role from "@lang/modules/role";
import valueSet from "@lang/modules/valueSet";
import receiptSequence from "@lang/modules/receiptSequence";
import userManage from "@lang/modules/userManage";

export default {
  components: {},
  locales: {
    "zh-CN": {
      module: {
        receiptSequence: receiptSequence["zh-CN"],
        role: role["zh-CN"],
        valueSet: valueSet["zh-CN"],
        userManage: userManage["zh-CN"]
      }
    },
    "en-US": {
      module: {
        receiptSequence: receiptSequence["en-US"],
        role: role["en-US"],
        valueSet: valueSet["en-US"],
        userManage: userManage["en-US"]
      }
    }
  },
  props: {
    existingData: {
      type: Array,
      default: []
    },
    ruleId: {
      type: String,
      default() {
        return "";
      }
    },
    receiptSeqCode: {
      type: String,
      default() {
        return "";
      }
    }
  },
  data() {
    const ruleSegmentFieldValid = (rule, value, callback) => {
      if (!this.segmentFieldValueNoEdit) {
        if (value === "" || value === null || value === undefined) {
          callback(new Error(this.$t("module.receiptSequence.enterFieldValue")));
        } else if (value.length > 50) {
          callback(new Error(this.$t("module.receiptSequence.fieldValueMaxLength")));
        } else if (!new RegExp("^([a-zA-z0-9]|_|-)+$").test(value)) {
          callback(new Error(this.$t("module.receiptSequence.consistOfFieldValue")));
        }
        callback();
      } else {
        callback();
      }
    };
    const seqLengthValid = (rule, value, callback) => {
      if (!this.seqLengthNoEdit) {
        if (value === "" || value === null || value === undefined) {
          callback(new Error(this.$t("module.receiptSequence.enterDigit")));
        } else if (!new RegExp("^[0-9]+$").test(Number(value))) {
          callback(new Error(this.$t("module.receiptSequence.onlyNumber")));
        }
        callback();
      } else {
        callback();
      }
    };
    const datePatternValid = (rule, value, callback) => {
      if (!this.datePatternNoEdit) {
        if (value === "" || value === null || value === undefined) {
          callback(new Error(this.$t("module.receiptSequence.enterDateFormat")));
        }
        callback();
      } else {
        callback();
      }
    };
    const seqIncrementValid = (rule, value, callback) => {
      if (!this.seqIncrementNoEdit) {
        if (value === "" || value === null || value === undefined) {
          callback(new Error(this.$t("module.receiptSequence.enterStepSize")));
        } else if (!new RegExp("^[0-9]+$").test(value)) {
          callback(new Error(this.$t("module.receiptSequence.onlyNumber")));
        }
        callback();
      } else {
        callback();
      }
    };
    const seqStartValueValid = (rule, value, callback) => {
      if (!this.seqStartValueNoEdit) {
        if (value === "" || value === null || value === undefined) {
          callback(new Error(this.$t("module.receiptSequence.enterStartValue")));
        } else if (!new RegExp("^[0-9]+$").test(Number(value))) {
          callback(new Error(this.$t("module.receiptSequence.onlyNumber")));
        }
        callback();
      } else {
        callback();
      }
    };

    const ruleSegmentOrderValid = (rule, value, callback) => {
      let conflict = false;
      for (let item of this.existingData) {
        if ((item.id || item.ruleId) != this.ruleId && item.ruleSegmentOrder === value) {
          conflict = true;
          break;
        }
      }

      if (conflict) {
        callback(new Error(this.$t("module.receiptSequence.orderConflicted")));
      } else {
        callback();
      }
    };
    const parameterCodeValueValid = (rule, value, callback) => {
      if (!this.parameterCodeValueEdit) {
        if (value === "") {
          callback(new Error(this.$t("module.receiptSequence.enterparameterCode")));
        }
        callback();
      } else {
        callback();
      }
    };
    Date.prototype.format = function(fmt) {
      var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds() //毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
      }
      return fmt;
    };

    return {
      modelForm: {
        ruleSegmentField: "",
        ruleSegmentFieldValue: "",
        datePattern: "",
        seqIncrement: null,
        seqStartValue: null,
        seqLength: null,
        paramCode: "",
        paramName: "",
        paramDefaultValue: "",
        ruleId: this.ruleId,
        receiptSeqCode: this.receiptSeqCode,
        enabled: 1,
        ruleSegmentOrder: 1
      },
      //  parameterDefaultInput: null,
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ],
      segmentList: [],
      segmentFieldValueNoEdit: true, //段值
      datePatternNoEdit: true, //日期格式
      seqLengthNoEdit: true, //位数
      seqIncrementNoEdit: true, //步长
      seqStartValueNoEdit: true, //开始值
      parameterCodeValueEdit: true, //参数代码
      parameterNameInputEdit: true, //参数名称,
      parameterDefaultInputEdit: true, //参数默认值
      dateFormatList: [],
      rule: {
        ruleSegmentField: [{ required: true, message: this.$t("module.receiptSequence.selectField"), trigger: "blur" }],
        ruleSegmentFieldValue: [
          { required: !this.segmentFieldValueNoEdit, validator: ruleSegmentFieldValid, trigger: "blur" }
        ],
        datePattern: [{ required: true, validator: datePatternValid, trigger: "blur" }],
        seqIncrement: [{ required: true, validator: seqIncrementValid, trigger: "blur" }],
        seqLength: [{ required: true, validator: seqLengthValid, trigger: "blur" }],
        seqStartValue: [{ required: true, validator: seqStartValueValid, trigger: "blur" }],
        ruleSegmentOrder: [{ required: true, validator: ruleSegmentOrderValid, trigger: "blur" }],
        paramCode: [{ required: true, validator: parameterCodeValueValid, trigger: "blur" }]
      }
    };
  },
  computed: {},
  created: function() {
    this.initDateFormat();
    if (!!this.ruleId) {
      this.$emit("SetTitle", this.$t("module.receiptSequence.updateRule"));
      // 请求数据
      $http.post(`${window.RPConfig.setting}/sys/receiptSeq/rule/query`, { id: this.ruleId }).then(response => {
        response = response.data;
        console.log("response", response);
        this.segmentChange(response[0].ruleSegmentField);
        this.modelForm = response[0];
        if (response[0].ruleSegmentField === "SEQENCE_NO") {
          this.modelForm.seqIncrement = response[0].seqIncrement + ''
          this.modelForm.seqLength = response[0].seqLength + ''
          this.modelForm.seqStartValue = response[0].seqStartValue + ''
        }
        
      });
    } else {
      this.$emit("SetTitle", this.$t("module.receiptSequence.addRule"));
    }
    this.$emit("SetPageWidth", 700);
    this.$emit("SetPageActions", this.actions);
    GetValueSetByCode({ code: "RULE_SEGMENT" }).then(response => {
      this.segmentList = response;
    });
  },
  // beforeMount: function() {},
  // mounted: function() {},
  // beforeDestroy: function() {},
  // destroyed: function() {},
  methods: {
    // 初始化日期格式
    initDateFormat() {
      GetValueSetByCode({ code: "dateFormat" }).then(data => {
        this.dateFormatList = data;
      });
    },
    // 编辑和添加
    save() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (!!this.ruleId) {
            $http
              .post(`${window.RPConfig.setting}/sys/receiptSeq/rule/update`, this.modelForm)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("module.receiptSequence.updateSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(err => {
                this.actions[0].loading = false;
              });
          } else {
            $http
              .post(`${window.RPConfig.setting}/sys/receiptSeq/rule/save`, this.modelForm)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("module.receiptSequence.createSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(err => {
                this.actions[0].loading = false;
              });
          }
        }
      });
    },
    // 段 选框改变的方法（DATE_PATTERN：日期格式，SEQENCE_NO：序列号，FIX_CHARACTER：固定字符）
    segmentChange(data) {
      if (data == "DATE_PATTERN") {
        this.segmentFieldValueNoEdit = true; //段值
        this.modelForm.ruleSegmentFieldValue = "";
        this.datePatternNoEdit = false; //日期格式
        this.seqLengthNoEdit = true; //位数
        this.modelForm.seqLength = null;
        this.seqIncrementNoEdit = true; //步长
        this.modelForm.seqIncrement = null;
        this.seqStartValueNoEdit = true; //开始值
        this.modelForm.seqStartValue = null;
        this.parameterCodeValueEdit = true; //参数代码
        this.parameterNameInputEdit = true; //参数名称,
        this.parameterDefaultInputEdit = true; //参数默认值
      } else if (data == "SEQENCE_NO") {
        //**********************************正整数 */
        this.segmentFieldValueNoEdit = true; //段值
        this.modelForm.ruleSegmentFieldValue = "";
        this.datePatternNoEdit = true; //日期格式************************下拉框
        this.modelForm.datePattern = "";
        this.seqLengthNoEdit = false; //位数
        this.seqIncrementNoEdit = false; //步长
        this.seqStartValueNoEdit = false; //开始值
        this.parameterCodeValueEdit = true; //参数代码
        this.parameterNameInputEdit = true; //参数名称,
        this.parameterDefaultInputEdit = true; //参数默认值
      } else if (data == "FIX_CHARACTER") {
        this.segmentFieldValueNoEdit = false; //段值
        this.datePatternNoEdit = true; //日期格式
        this.modelForm.datePattern = "";
        this.seqLengthNoEdit = true; //位数
        this.modelForm.seqLength = null;
        this.seqIncrementNoEdit = true; //步长
        this.modelForm.seqIncrement = null;
        this.seqStartValueNoEdit = true; //开始值
        this.modelForm.seqStartValue = null;
        this.parameterCodeValueEdit = true; //参数代码
        this.parameterNameInputEdit = true; //参数名称,
        this.parameterDefaultInputEdit = true; //参数默认值
      } else if (data == "PARAMETER") {
        this.parameterCodeValueEdit = false; //参数代码
        this.parameterNameInputEdit = false; //参数名称,
        this.parameterDefaultInputEdit = false; //参数默认值
        this.modelForm.ruleSegmentFieldValue = "";
        this.segmentFieldValueNoEdit = true; //段值
        this.seqLengthNoEdit = true; //位数
        this.seqIncrementNoEdit = true; //步长
        this.seqStartValueNoEdit = true; //开始值
        this.datePatternNoEdit = true; //日期格式
        this.modelForm.datePattern = "";
      }
    },
    dataChange() {
      // //console.log(new Date().format('yyyy-MM-dd'))
      //  if(new Date().format(this.modelForm.datePattern) && this.modelForm.datePattern != new Date().format(this.modelForm.datePattern)){
      //    //console.log(new Date().format(this.modelForm.datePattern))
      //    //console.log("成功了")
      //  };
    }
  },
  watch: {},
  directives: {}
};
</script>
